#include "udpwork.h"
#include "utils.h"
#include <QTime>

UDPWork::UDPWork(QObject *parent) : QObject(parent)
{
    udp_socket = new QUdpSocket(this);
    udp_socket->bind(localAddress, 12345);
    shakeStringFrom = "I am MRI System Hololens2";
    shakeStringTo =  "I am MRI System PC";
    connect(udp_socket, &QUdpSocket::readyRead, this, &UDPWork::receive_data_slot);
}

void UDPWork::send_Broadcast_slot()
{
    try
    {
        QByteArray datagram = shakeStringTo.toLocal8Bit();
        udp_socket->writeDatagram(datagram, datagram.size(), QHostAddress::Broadcast, 24510);
     }
    catch (const std::exception& e)
    {
        emit update_textBrowser_signal(QString::fromUtf8(e.what()));
    }

}

void UDPWork::send_Message_slot(QString meg)
{
    try
    {
        QByteArray datagram = meg.toLocal8Bit();
        udp_socket->writeDatagram(datagram, remoteAddress , 24510);
     }
    catch (const std::exception& e)
    {
        emit update_textBrowser_signal(QString::fromUtf8(e.what()));
    }

}

void UDPWork::receive_data_slot()
{
    while (udp_socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udp_socket->pendingDatagramSize());
        udp_socket->readDatagram(datagram.data(), datagram.size());

        if (datagram.data() != nullptr && datagram.size() > 0) // 防止空响应
        {
            QString message_body = QString(datagram);

            if (message_body.contains(shakeStringFrom))
            {
               QString remoteIP = message_body.mid(shakeStringFrom.length(),
                                            message_body.length() - shakeStringFrom.length());

                emit detain_ClientIP_signal(remoteIP);
                remoteAddress = QHostAddress(remoteIP);
            }
            else
            {
                emit update_textBrowser_signal("udp recv string: " + message_body);
            }

        }

    }
}

void UDPWork::Update_IP_slot(QString ip)
{
    localIP = ip;
}
